import sounddevice as sd
import numpy as np
from time import sleep


def set_output():
    """
    自动搜索电脑自带扬声器的设备序号，如果搜索不到，则使用默认输出设备。
    Automatically search for the device serial number of the computer's built-in speaker,
    if not found, use the default output device。
    :return: device index
    """
    device = sd.query_devices()
    device = iter(device)
    devicei = 0
    try:
        while next(device)['name'].find('扬声器') == -1:
            devicei += 1
    except StopIteration:
        devicei = sd.default.device[1]
    return devicei


if __name__ == '__main__':
    output = sd.OutputStream(device=set_output(), dtype="int8")  # 创建输出流 / Create output stream
    output.start()  # 开始输出 / Start output
    song = np.zeros((20000, 2), dtype="int8")  # 创建一段全零数组作为无声音频 / Create an array of all zeros as silent audio
    while True:
        try:
            output.write(song)  # 输出无声音频 / Output silent audio
        except OSError:  # 若输出中断，则重新创建输出流 / If the output is interrupted, re-create the output stream
            output = sd.OutputStream(device=set_output(), dtype="int8")
            output.start()
        sleep(1)
